package com.cr.web.controller.api;

import com.cr.business.service.SmsService;
import com.cr.common.constant.CacheConstants;
import com.cr.common.constant.Constants;
import com.cr.common.constant.RegConstants;
import com.cr.common.core.domain.AjaxResult;
import com.cr.common.core.redis.RedisCache;
import com.cr.common.utils.uuid.IdUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("api")
@Validated
public class SMSController {

    @Resource
    private RedisCache redisCache;

    @Resource
    private SmsService smsService;

    /**
     * 获取验证码
     */
    @GetMapping("getSMSCode")
    public AjaxResult getCode(
            @NotBlank(message = "手机号不能为空!")
            @Pattern(regexp = RegConstants.PHONE_NUMBER, message = "手机号格式有误！") String phone) {

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.SMS_CODE_KEY + uuid;
        String code = IdUtils.generateVerificationCode();
        try {
            boolean success = smsService.sendSms(phone, code, Constants.SMS_EXPIRATION);
            if (success) {
                redisCache.setCacheObject(verifyKey, code, Constants.SMS_EXPIRATION, TimeUnit.MINUTES);
                Map<String, Object> data = new HashMap<>();
                data.put("uuid", uuid);
                data.put("expiration", Constants.SMS_EXPIRATION);
                return AjaxResult.success(data);
            } else {
                return AjaxResult.error("短信发送失败！");
            }
        } catch (Exception e) {
            return AjaxResult.error("短信发送异常：" + e.getMessage());
        }
    }
}
